//
//  LXPhotosView.m
//  微了个小博
//
//  Created by imera on 15/10/17.
//  Copyright (c) 2015年 imera. All rights reserved.
//

#import "LXPhotosView.h"
#import "LXPhotoView.h"
#import "MJPhoto.h"
#import "LXPhoto.h"
#import "MJPhotoBrowser.h"

@implementation LXPhotosView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self){
        //初始化9个子控件
        for (int i=0; i<9; i++) {
            LXPhotoView *photoView = [[LXPhotoView alloc]init];
            photoView.hidden = YES;
            photoView.userInteractionEnabled = YES;
            [photoView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapView:)]];
            photoView.tag = i;
            
            [self addSubview:photoView];
        }
    }
    return self;
}

- (void)tapView:(UITapGestureRecognizer *)recognizer
{
    CGFloat count = self.pic_urls.count;
    //1.封装图片数据
    NSMutableArray *myPhotos = [NSMutableArray array];
    for (int i=0; i<count; i++) {
        LXPhotoView *photoView = self.subviews[i];
        
        MJPhoto *mjPhoto = [[MJPhoto alloc]init];
        mjPhoto.srcImageView = photoView;
        NSString *url = [photoView.photo.thumbnail_pic stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
        mjPhoto.url = [NSURL URLWithString:url];
        
        [myPhotos addObject:mjPhoto];
    }
    
    //2.显示相册
    MJPhotoBrowser *photoBrowser = [[MJPhotoBrowser alloc]init];
    photoBrowser.currentPhotoIndex = recognizer.view.tag;
    photoBrowser.photos = myPhotos;
    [photoBrowser show];
}

- (void)setPic_urls:(NSArray *)pic_urls
{
    _pic_urls = pic_urls;
    
    //给子控件添加数据
    for (int i=0; i<self.subviews.count; i++) {
        LXPhotoView *photoView = self.subviews[i];
        if(i < pic_urls.count){
            photoView.hidden = NO;
            photoView.photo = pic_urls[i];
            
            //设置photo的Frame
            int maxCloumns = (pic_urls.count == 4) ? 2 : 3;
            int clo = i % maxCloumns;
            int row = i / maxCloumns;
            CGFloat W = LXPhotoWidth;
            CGFloat H = LXPhotoHeight;
            CGFloat X = clo * (W + LXMargin);
            CGFloat Y = row * (H + LXMargin);
        
            photoView.frame = CGRectMake(X, Y, W, H);

            if(pic_urls.count == 1){
                photoView.contentMode = UIViewContentModeScaleAspectFit;
                photoView.clipsToBounds = NO;
            }else{
                photoView.contentMode = UIViewContentModeScaleAspectFill;
                photoView.clipsToBounds = YES;
            }
        }else{
            photoView.hidden = YES;
        }
    }
}

@end
